import Switch from '@material-ui/core/Switch';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import Alert from '@material-ui/lab/Alert';
import Select from '@material-ui/core/Select';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import InputLabel from '@material-ui/core/InputLabel';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import InputAdornment from '@material-ui/core/InputAdornment';
import SearchIcon from '@material-ui/icons/Search';
import IconButton from '@material-ui/core/IconButton';
import TextField from '@material-ui/core/TextField';
import MenuItem from '@material-ui/core/MenuItem';
import React, { useState, useEffect } from 'react';
import { DlgFind, loc, obj_str, is_empty } from 'sui';

const KInput = ({ className, form, label, name, width="w-px-dlg", mg="normal", disabled, type="text", href, mul=false }) => {
    const [err, setErr] = useState(false);
    const [err_txt, errTxt] = useState("");

    useEffect(() => {
        const e = obj_str(form.err, name);
        if (e === err_txt) {
            return;
        }

        if (e) {
            setErr(true);
            errTxt(e);
        }
        else {
            setErr(false);
            errTxt("");
        }
    }, [name, form.err, err_txt]);

    if (mul) {
        return (
            <div className={className}>
                <TextField
                multiline
                disabled={disabled}
                margin={mg}
                variant="outlined"
                type={type}
                className={width}
                name={name}
                error={err}
                helperText={err_txt}
                value={form.get(name)}
                inputRef={href}
                onChange={({ target:{ value }}) => form.set(name, value)}
                label={label}/>
            </div>
        );
    }

    return (
        <div className={className}>
            <TextField
            disabled={disabled}
            margin={mg}
            variant="outlined"
            type={type}
            className={width}
            name={name}
            error={err}
            helperText={err_txt}
            value={form.get(name)}
            inputRef={href}
            onChange={({ target:{ value }}) => form.set(name, value)}
            label={label}/>
        </div>
    );
};

/* lst = [
 *   {sn: "xx", name: "xx"}
 * ]
*/
const KSelect = ({ form, label, lst, name, className, width="w-px-dlg", mg, disabled=false }) => {
    const [err, setErr] = useState(false);
    const [err_txt, errTxt] = useState("");

    useEffect(() => {
        const e = obj_str(form.err, name);
        if (e === err_txt) {
            return;
        }

        if (e) {
            setErr(true);
            errTxt(e);
        }
        else {
            setErr(false);
            errTxt("");
        }
    }, [name, form.err, err_txt]);

    const item = () => {
        if (is_empty(lst)) {
            return null;
        }

        return lst.map(d => <MenuItem key={d.sn} value={d.sn}>{d.name}</MenuItem>);
    };

    return (
        <div className={className}>
            <FormControl variant="outlined" className={width} error={err} disabled={disabled}>
                <InputLabel margin={mg}>{label}</InputLabel>
                <Select
                    margin={mg}
                    value={form.get(name)}
                    name={name}
                    label={label}
                    onChange={({ target:{ value }}) => form.set(name, value)}>
                    {item()}
                </Select>
                <FormHelperText>{err_txt}</FormHelperText>
            </FormControl>
        </div>
    );
};

const KSwitch = ({ className, children, disabled, form, name }) => {
    const hcmd = (event) => {
        const b = event.target.checked;
        form.set(name, b ? "Y" : "N");
    };

    const getCheck = () => {
        return form.get(name) === "Y";
    };

    return (
        <div className={className}>
            <Switch name={name} disabled={disabled} checked={getCheck()} onChange={hcmd} color="primary"/>
            <span className="text-base">{children}</span>
        </div>
    );
}

const KFind = ({ hcmd, className, form, label, name, width="w-px-dlg", margin="normal", list, c1="SN", c2=loc("l_228"), disabled, ext=[], dw="sm" }) => {
    const [open, setOpen] = useState(false);

    useEffect(() => {
        setOpen(false);
    }, []);

    const getVal = () => {
        if (is_empty(list)) {
            return "";
        }

        const sn = form.get(name);
        const f = list.find(d => d.sn === sn);
        if (!f) {
            return "";
        }

        let v = obj_str(f, "sn");
        const t = obj_str(f, "name");
        if (t) {
            v = `${v} ( ${t} )`;
        }

        return v;
    };

    const getInfo = () => {
        const info = obj_str(form.err, name);
        if (info) {
            return <FormHelperText>{info}</FormHelperText>;
        }

        return null;
    };

    const sz = margin === "dense" ? "small" : "medium";

    return (
        <div className={className}>
            <FormControl margin={margin} variant="outlined" className={width} error={Boolean(form.err[name])}>
                <InputLabel>{label}</InputLabel>
                <OutlinedInput
                    disabled={true}
                    name={name}
                    type="text"
                    value={getVal()}
                    endAdornment={
                        <InputAdornment position="end">
                            <IconButton size={sz} onClick={() => setOpen(true)} name={`btn${name}`} disabled={disabled}>
                                <SearchIcon fontSize={sz}/>
                            </IconButton>
                        </InputAdornment>
                    }
                    label={label}
                />
                {getInfo()}
            </FormControl>
            <DlgFind open={open} setOpen={setOpen} data={form.get(name)} main={list} title={label} hcmd={v => form.set(name, v)}
                c1={c1} c2={c2} ext={ext} width={dw}/>
        </div>
    );
};

const KRadioGroup = ({ children, name, form }) => {
    const hcmd = (event) => {
        form.set(name, event.target.value);
    };

    const getErr = () => {
        const e = obj_str(form.err, name);
        if (!e) {
            return null;
        }

        return <Alert severity="error" className="text-1xl mb-4">{obj_str(form.err, name)}</Alert>;
    };

    return (
        <FormControl>
            <RadioGroup value={form.get(name)} onChange={hcmd}>
                {children}
            </RadioGroup>
            {getErr()}
        </FormControl>
    );
};

const KRadio = ({ label, value }) => <FormControlLabel value={value} control={<Radio/>} label={label}/>;

const KFindCtl = ({ className, value, setValue, label, width="w-px-dlg", margin="normal", list }) => {
    const [open, setOpen] = useState(false);

    useEffect(() => {
        setOpen(false);
    }, []);

    const getVal = () => {
        if (is_empty(list)) {
            return "";
        }

        const f = list.find(d => d.sn === value);
        if (!f) {
            return "";
        }

        let v = obj_str(f, "sn");
        const t = obj_str(f, "name");
        if (t) {
            v = `${v} ( ${t} )`;
        }

        return v;
    };

    const sz = margin === "dense" ? "small" : "medium";

    return (
        <div className={className}>
            <FormControl margin={margin} variant="outlined" className={width}>
                <InputLabel>{label}</InputLabel>
                <OutlinedInput
                    disabled={true}
                    type="text"
                    value={getVal()}
                    endAdornment={
                        <InputAdornment position="end">
                            <IconButton size={sz} onClick={() => setOpen(true)}>
                                <SearchIcon fontSize={sz}/>
                            </IconButton>
                        </InputAdornment>
                    }
                    label={label}
                />
            </FormControl>
            <DlgFind open={open} setOpen={setOpen} data={value} main={list} title={label} hcmd={v => setValue(v)}/>
        </div>
    );
};

export {KFindCtl, KRadioGroup, KRadio, KFind, KSwitch, KSelect, KInput};
